package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author TieZhu
 * @since 2021-06-10
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Resource
    private RedisTemplate redisTemplate;

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class,new ExcelDictDTOListener(baseMapper)).sheet().doRead();
        log.info("导入数据完成");
    }

    @Override
    public List<ExcelDictDTO> listDictData() {
        List<Dict> dictList = baseMapper.selectList(null);
        List<ExcelDictDTO> excelDictDTOList=new ArrayList<>();
        dictList.forEach(dict -> {
            ExcelDictDTO excelDictDTO=new ExcelDictDTO();
            BeanUtils.copyProperties(dict,excelDictDTO);
            excelDictDTOList.add(excelDictDTO);
        });
        return excelDictDTOList;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {
        List<Dict> dictList = null;
        try {
            dictList=(List<Dict>)redisTemplate.opsForValue().get("srb:core:dictList:"+parentId);
            if (dictList!=null){
                log.info("从Redis中取值");
                return dictList;
            }
        }catch (Exception e){
            log.error("Redis服务异常："+ ExceptionUtils.getStackTrace(e));
        }

        log.info("从数据库中取值");
        dictList=baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", parentId));
        dictList.forEach(dict -> {
            boolean hashChildren=this.hashChildren(dict.getId());
            dict.setHasChildren(hashChildren);
        });

        try {
            redisTemplate.opsForValue().set("srb:core:dictList:"+parentId,dictList,6, TimeUnit.HOURS);
        }catch (Exception e){
            log.error("Redis服务异常："+ ExceptionUtils.getStackTrace(e));
        }

        return dictList;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        System.out.println(dictCode);
        queryWrapper.eq("dict_code",dictCode);
        Dict one = baseMapper.selectOne(queryWrapper);
        queryWrapper.clear();
        queryWrapper.eq("parent_id",one.getId());
        List<Dict> dicts = baseMapper.selectList(queryWrapper);
        return dicts;
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {
        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dict_code",dictCode);
        Dict parentDict=baseMapper.selectOne(queryWrapper);
        if (parentDict==null){
            return "";
        }
        queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parent_id",parentDict.getId()).eq("value",value);
        Dict dict=baseMapper.selectOne(queryWrapper);
        if (dict==null){
            return "";
        }
        System.out.println("msg"+dict.getName());
        return dict.getName();
    }

    private boolean hashChildren(Long id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<Dict>().eq("parent_id", id);
        Integer count=baseMapper.selectCount(queryWrapper);
        if (count.intValue()>0){
            return true;
        }else {
            return false;
        }
    }

}
